package com.rc.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.rc.activity.dao.tbl_Settings;
import com.rc.activity.dao.tbl_User;
import com.rc.activity.provider.Contract;
import com.rc.db.DatabaseSupport;
import com.rc.model.Model;
import com.rc.model.TaskType;
import com.rc.util.Const;
import com.rc.util.Util;
import com.telpoo.frame.model.TaskParams;
import com.telpoo.frame.ui.BaseActivity;

public class Settings extends BaseActivity implements OnClickListener {

	private LinearLayout llLogOut, llSaveGeneral, llProgress, llSaveAccount,
			llAccountTitle, llAccount, llGeneralTitle, llGeneral;
	private TextView txtCurrencyCode, txtNewPassword, txtRetypePassword,
			txtCurrentPassword;
	private Spinner spTimeZone, spMultiLanguage;
	private ScrollView scContent;
	private int row;
	private tbl_Settings objSettings;

	public static void callIntent(Context ct) {
		Intent it = new Intent(ct, Settings.class);
		it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		it.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		ct.startActivity(it);
	}

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main_settings);

		// register
		llSaveGeneral = (LinearLayout) findViewById(R.id.llSaveGeneral);
		llSaveAccount = (LinearLayout) findViewById(R.id.llSaveAccount);
		llAccount = (LinearLayout) findViewById(R.id.llAccount);
		llAccountTitle = (LinearLayout) findViewById(R.id.llAccountTitle);
		llGeneral = (LinearLayout) findViewById(R.id.llGeneral);
		llGeneralTitle = (LinearLayout) findViewById(R.id.llGeneralTitle);
		llLogOut = (LinearLayout) findViewById(R.id.llLogOut);
		llProgress = (LinearLayout) findViewById(R.id.llProgress);
		scContent = (ScrollView) findViewById(R.id.scContent);
		spMultiLanguage = (Spinner) findViewById(R.id.spMultiLanguage);
		spTimeZone = (Spinner) findViewById(R.id.spTimeZone);
		txtNewPassword = (TextView) findViewById(R.id.txtNewPassword);
		txtRetypePassword = (TextView) findViewById(R.id.txtRetypePassword);
		txtCurrentPassword = (TextView) findViewById(R.id.txtCurrentPassword);
		txtCurrencyCode = (TextView) findViewById(R.id.txtCurrencyCode);

		// function onclick
		llSaveGeneral.setOnClickListener(this);
		llLogOut.setOnClickListener(this);
		llSaveAccount.setOnClickListener(this);
		llGeneralTitle.setOnClickListener(this);
		llAccountTitle.setOnClickListener(this);
		// funtion
		objSettings = new tbl_Settings();
		objSettings = getDataSqlite();
		if (objSettings == null) {
			return;
		}
		String timezone = objSettings.getTimezone();
		if ("".equals(timezone)) {
			Calendar cal = Calendar.getInstance();
			TimeZone tz = cal.getTimeZone();
			timezone = tz.getID();
		}
		ArrayAdapter<String> adpTimeZone = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item,
				getAssetTiemZone(timezone));
		adpTimeZone
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spTimeZone.setAdapter(adpTimeZone);
		spTimeZone.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});
		spTimeZone.setSelection(row);

		// spinner multi laguage
		ArrayAdapter<String> adpMultiLaguage = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, getResources()
						.getStringArray(R.array.multi_language));
		adpMultiLaguage
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spMultiLanguage.setAdapter(adpMultiLaguage);
		spMultiLanguage.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});
		spMultiLanguage.setSelection(0);
		txtCurrencyCode.setText(objSettings.getCurrencyCode());

	}

	public void changeLang(int pos) {
		String langue = Const.LANGUAGE_CODE[pos];
		if (langue.equalsIgnoreCase(""))
			return;
		Locale myLocale = new Locale(langue);
		Locale.setDefault(myLocale);
		android.content.res.Configuration config = new android.content.res.Configuration();
		config.locale = myLocale;
		Settings.this.getResources().updateConfiguration(config,
				Settings.this.getResources().getDisplayMetrics());
	}

	/**
	 * get data in currency.txt what in asset
	 */
	private ArrayList<String> getAssetTiemZone(String timeZone) {
		ArrayList<String> arrString = new ArrayList<String>();
		arrString = Util.readFromfile(Settings.this, "timezone-list.txt");
		ArrayList<String> arrCurrency = new ArrayList<String>();
		for (int i = 0; i < arrString.size(); i++) {
			String line = "";
			line = arrString.get(i);
			String[] lText = null;
			lText = line.split(":");
			line = lText[0];
			line = line.replace("\"", "");
			arrCurrency.add(line.trim());
			if (timeZone.equals(line.trim())) {
				row = i;
			}
		}
		return arrCurrency;
	}

	/**
	 * get data tbl_setting in sqlite
	 */

	private tbl_Settings getDataSqlite() {
		tbl_Settings objSetting = new tbl_Settings();
		Cursor cursor = this.getContentResolver().query(
				Contract.CONTENT_URI_SETTING, null, null, null, null);
		objSetting = tbl_Settings.getObjectByCursor(cursor);
		return objSetting;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.llSaveAccount:
			callAsynCallservice();
			break;
		case R.id.llCancel:
			finish();
			break;
		case R.id.llLogOut:
			callAsynCallServiceDeleteDevice();
			break;
		case R.id.llSaveGeneral:
			objSettings.setTimezone(spTimeZone.getSelectedItem().toString());
			objSettings.setCurrencyCode(txtCurrencyCode.getText().toString());
			objSettings.setIsUpdate("1");
			if (this.getContentResolver().update(Contract.CONTENT_URI_SETTING,
					objSettings.getContentValues(), null, null) > 0) {
				finish();
			}
			break;
		case R.id.llAccountTitle:
			if (llAccount.getVisibility() == View.GONE) {
				llAccount.setVisibility(View.VISIBLE);
				llGeneral.setVisibility(View.GONE);
			} else {
				llAccount.setVisibility(View.GONE);
			}
			break;
		case R.id.llGeneralTitle:
			if (llGeneral.getVisibility() == View.GONE) {
				llGeneral.setVisibility(View.VISIBLE);
				llAccount.setVisibility(View.GONE);
			} else {
				llGeneral.setVisibility(View.GONE);
			}
			break;

		default:
			break;
		}
	}

	@Override
	public void onSuccess(int taskType, ArrayList<?> list, String msg) {
		super.onSuccess(taskType, list, msg);
		switch (taskType) {
		case TaskType.TASK_CHANGE_PASS:
			finish();
			break;

		default:
			break;
		}
	}

	@Override
	public void onFail(int taskType, String msg) {
		super.onFail(taskType, msg);
		switch (taskType) {
		case TaskType.TASK_CHANGE_PASS:
			showToast(msg);
			break;
		case TaskType.TASK_DELETE_DEVICE:
			showToast(msg);
			break;
		default:
			break;
		}
		llProgress.setVisibility(View.GONE);
		scContent.setVisibility(View.VISIBLE);
	}

	/**
	 * call sevirce receipt
	 */
	private void callAsynCallServiceDeleteDevice() {
		if ("".equals(Const.AUTHENKEY)) {
			tbl_User objUser = new tbl_User();
			objUser = DatabaseSupport.getTbl_User(Settings.this);
			if (objUser == null) {
				return;
			}
			Const.AUTHENKEY = objUser.getToken();
		}
		Model mModel = new Model(model, TaskType.TASK_DELETE_DEVICE, null, this);
		String deviceToken = DatabaseSupport.getTbl_User(Settings.this)
				.getDeviceToken();
		if (deviceToken == null) {
			showToast(getString(R.string.no_device));
			return;
		} else {
			if (deviceToken.equals("")) {
				showToast(getString(R.string.no_device));
				return;
			}
		}

		String[] mParams = { deviceToken };
		TaskParams params = new TaskParams(mParams);
		if (Util.isNetworkActivated(Settings.this)) {
			llProgress.setVisibility(View.VISIBLE);
			scContent.setVisibility(View.GONE);
			model.exeTask(params, mModel);
		} else {
			showToast(getString(R.string.no_connection));
		}
	}

	private void callAsynCallservice() {
		String[] param = { txtCurrentPassword.getText().toString(),
				txtNewPassword.getText().toString(),
				txtRetypePassword.getText().toString() };
		Model mModel = new Model(model, TaskType.TASK_CHANGE_PASS, null, this);
		TaskParams params = new TaskParams(param);
		if (Util.isNetworkActivated(Settings.this)) {
			llProgress.setVisibility(View.VISIBLE);
			scContent.setVisibility(View.GONE);
			model.exeTask(params, mModel);
		} else {
			showToast(getString(R.string.no_connection));
		}
	}
}
